<?php defined('SYSPATH') or die('No direct script access.');

class Product_Controller extends Template_Controller 
{
	public function __construct()
	{
		parent::__construct();

		$this->template->menu = new View('menu');
	}
	
	public function index()
	{		
		self::page(1);
	}
	
	public function page($page_no)
	{
	    $block = new Block_Model();
	    $product = new Product_Model();
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'product/page/', // Set our base URL to controller 'items' and method 'page'
	        'uri_segment' => 'page', // Our URI will look something like http://domain/items/page/19
			'items_per_page' => 10, 
	        'total_items' => $product->select('COUNT(*) AS records_found')->find()->records_found // Total number of items.
	    ));
	 
		$view = new View('product/lists');
		$view->caption = 'Product List';
		$view->datas = $product->orderby('updated_at', 'DESC')->limit(10, (($page_no - 1) * 10))->find_all();
		$view->categories = self::getProductCategory();
		$view->series = self::getProductSeries();
		$view->blocks = self::getBlocksBySourceName('products');
		$view->type = '';
		$view->id = '';
		
		$this->template->content = $view->render();
	}
	
	public function view($id)
	{
		$product = new Product_Model($id);
		
		$view = new View('product/view');
		$view->product = $product;
		
		$this->template->content = $view->render();
	}
	
	public function create()
	{
		$title = 'title_'.cookie::get('lang');
		
		$form = new Forge(NULL, 'New Product');
		$form->input('name')->label(TRUE);
		$form->input('series')->label('系列');
		$form->dropdown('category_id')->label('分类')->options(self::getProductCategory())->rules('required');
		$form->input('title_cn')->label('中文标题')->rules('required');
		$form->input('title_en')->label('英文标题')->rules('required');
		$form->input('quantity')->label('数量')->rules('required|valid_numeric')->value(0);
		$form->input('weight')->label('重量')->rules('required|valid_numeric')->value(0);
		$form->input('market_price')->label('市场价格')->rules('required|valid_numeric');
		$form->input('price')->label('价格')->rules('required|valid_numeric');
		$form->textarea('description_cn')->label('中文介绍');
		$form->textarea('description_en')->label('英文介绍');
		$form->textarea('keywords')->label('关键词');
		$form->input('author_cn')->label('作者（中文）');
		$form->input('author_en')->label('作者（英文）');
		$form->input('publisher_cn')->label('出版社（中文）');
		$form->input('publisher_en')->label('出版社（英文）');
		$form->input('sku')->label('SKU');
		$form->input('extra_handling')->label('Extra Handling');
		
		$form->upload('file', TRUE)->label('Product Photo')->rules('size[2000KB]|allow[jpg,png,gif]');
		//$form->dateselect('available_at', TRUE)->label('Product Available Date')->years(date('Y'), date('Y')+20);
		$form->submit('Save');
 
		if($form->validate())
		{
			//Load model and set values
			$product = new Product_Model();
			$product->name = $form->name->value;
			$product->series = $form->series->value;
			$product->category_id = $form->category_id->value;
			$product->title_cn = $form->title_cn->value;
			$product->title_en = $form->title_en->value;
			$product->author_cn = $form->author_cn->value;
			$product->author_en = $form->author_en->value;
			$product->publisher_cn = $form->publisher_cn->value;
			$product->publisher_en = $form->publisher_en->value;
			$product->description_cn = $form->description_cn->value;
			$product->description_en = $form->description_en->value;
			$product->keywords = $form->keywords->value;
			$product->quantity = $form->quantity->value;
			$product->weight = $form->weight->value;
			$product->market_price = $form->market_price->value;
			$product->price = $form->price->value;
			$product->sku = $form->sku->value;
			$product->extra_handling = $form->extra_handling->value;
			$product->created_at = date('Y-m-d H:m:i');
			//$product->available_at = date('Y-m-d H:m:i', $form->available_at->value);
			$product->type_id = 2;
			 
			//Save form into table
			if($product->save())
			{
				self::setProductsCategories(0, $product->category_id, $product->id);
				
				if($form->file->value)
				{
					$filename = Config::item('product.original_photo_path').$product->id.'.'.file::extension($form->file->value);
					myfile::move($form->file->value, $filename);
					$product->photo_ext = file::extension($form->file->value);
					$product->save();
				}
					
				url::redirect('product/create', 301);
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->html();
		}
	}
	
	public function edit($id)
	{
		$product = new Product_Model($id);
		
		$old_category_id = $product->category_id;

		$form = new Forge(NULL, 'Edit Product');
		$form->input('name')->label(TRUE)->value($product->name);
		$form->input('series')->label('系列')->value($product->series);
		$form->dropdown('category_id')->label('分类')->options(self::getProductCategory())->rules('required')->value($product->category_id);
		$form->input('title_cn')->label('中文标题')->rules('required')->value($product->title_cn);
		$form->input('title_en')->label('英文标题')->rules('required')->value($product->title_en);
		$form->input('quantity')->label('数量')->rules('required|valid_numeric')->value($product->quantity);
		$form->input('weight')->label('重量')->rules('required|valid_numeric')->value($product->weight);
		$form->input('market_price')->label('市场价格')->rules('required|valid_numeric')->value($product->market_price);
		$form->input('price')->label('价格')->rules('required|valid_numeric')->value($product->price);
		$form->textarea('description_cn')->label('中文介绍')->value($product->description_cn);
		$form->textarea('description_en')->label('英文介绍')->value($product->description_en);
		$form->textarea('keywords')->label('关键词')->value($product->keywords);
		$form->input('author_cn')->label('作者（中文）')->value($product->author_cn);
		$form->input('author_en')->label('作者（英文）')->value($product->author_en);
		$form->input('publisher_cn')->label('出版社（中文）')->value($product->publisher_cn);
		$form->input('publisher_en')->label('出版社（英文）')->value($product->publisher_en);
		$form->input('sku')->label('SKU')->value($product->sku);
		$form->input('extra_handling')->label('Extra Handling')->value($product->extra_handling);
		
		$form->upload('file', TRUE)->label('Product Photo')->rules('size[200KB]|allow[jpg,png,gif]');
		//$form->dateselect('available_at', TRUE)->label('Product Available Date')->years(date('Y'), date('Y')+20)->value(strtotime($product->available_at));
		$form->submit('Save');
 
		if($form->validate())
		{
			$product->name = $form->name->value;
			$product->series = $form->series->value;
			$product->category_id = $form->category_id->value;
			$product->title_cn = $form->title_cn->value;
			$product->title_en = $form->title_en->value;
			$product->author_cn = $form->author_cn->value;
			$product->author_en = $form->author_en->value;
			$product->publisher_cn = $form->publisher_cn->value;
			$product->publisher_en = $form->publisher_en->value;
			$product->description_cn = $form->description_cn->value;
			$product->description_en = $form->description_en->value;
			$product->keywords = $form->keywords->value;
			$product->quantity = $form->quantity->value;
			$product->weight = $form->weight->value;
			$product->market_price = $form->market_price->value;
			$product->price = $form->price->value;
			$product->sku = $form->sku->value;
			$product->extra_handling = $form->extra_handling->value;
			$product->created_at = date('Y-m-d H:m:i');
			//$product->available_at = date('Y-m-d H:m:i', $form->available_at->value);
			//$product->type_id = $type_id;
			 
			if($product->save())
			{
				self::setProductsCategories($old_category_id, $product->category_id, $product->id);
				
				if($form->file->value)
				{
					$filename = Config::item('product.original_photo_path').$product->id.'.'.file::extension($form->file->value);
					myfile::move($form->file->value, $filename);
					$product->photo_ext = file::extension($form->file->value);
					$product->save();
				}

				url::redirect('product/view/'.$id);
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->html();
		}
	}
	
	public function category($product_id)
	{
		$product = new Product_Model($product_id);
		$category = new Product_Category_Model();
		
		$view = new View('product/product_category_lists');
	
		$view->caption = 'Product Category List：产品名称：'.$product->title_cn;
		$view->product = $product;
		$view->datas = $category->join('products_categories AS pcs', 'pcs.category_id=product_categories.id')
								->where('pcs.product_id', $product_id)
								->find_all();
		$view->categories = self::getProductCategory();
		
		$this->template->content = $view->render();
		
	}
	
	public function addcategory($product_id, $category_id)
	{
		$product = new Product_Model($product_id);
		
		self::setProductsCategories(0, $category_id, $product_id);
		
		url::redirect('product/category/'.$product_id);
		exit;
	}
	
	public function delcategory($product_id, $category_id)
	{
		$db = new Database();
		
		$db->query('DELETE FROM products_categories WHERE category_id='.$category_id.' AND product_id='.$product_id);
		
		url::redirect('product/category/'.$product_id);
		exit;
	}
	
	public function setcategorydefault($product_id, $category_id)
	{
		$product = new Product_Model($product_id);
		$product->category_id = $category_id;
		$product->save();
				
		url::redirect('product/category/'.$product_id);
		exit;

	}

	public function featured($category_id)
	{
		$product = new Product_Model();
		$category = new Product_Category_Model($category_id);
		
		if($category_id == 0)
			$category = $category->where('right_id-left_id=1')->limit(1)->find();
			
		$category_id = $category_id == 0 ? $category->id : $category_id;
		
		$view = new View('product/product_featured');
	
		$view->caption = '商品分类精品 －－－ '.$category->title_cn;
		$view->category = $category;
		$view->datas = $product->join('products_categories AS pcs', 'pcs.product_id=products.id')
							   ->where('pcs.category_id', $category_id)
							   ->where('pcs.featured', 1)
							   ->find_all();
		$view->categories = self::getProductCategory();
		
		$this->template->content = $view->render();
		
	}
	
	public function delfeatured($category_id, $product_id)
	{
		$db = new Database();
		
		$db->query('UPDATE products_categories SET featured=0 WHERE category_id='.$category_id.' AND product_id='.$product_id);
				
		url::redirect('product/featured/'.$category_id);
		exit;
	}
	
	public function setfeatured($category_id)
	{
		if(isset($_POST['product_id']) and intval($_POST['product_id']) > 0)
		{
			$db = new Database();
			$db->query('UPDATE products_categories SET featured=1 WHERE category_id='.$category_id.' AND product_id='.intval($_POST['product_id']));
		}
				
		url::redirect('product/featured/'.$category_id);
		exit;
	}
	
	protected function setProductsCategories($old_category_id, $category_id, $product_id)
	{
		if($old_category_id == $category_id)
			return;
		
		$db = new Database();
		
		$db->query('DELETE FROM products_categories WHERE category_id='.$old_category_id.' AND product_id='.$product_id);
		
		$has = $db->query('SELECT * FROM products_categories WHERE category_id='.$category_id.' AND product_id='.$product_id);
		
		if(count($has)==0)
		{
			$db->query('INSERT INTO products_categories (category_id, product_id) VALUES ('.$category_id.', '.$product_id.')');
		}
	}
	
	public function delete($id)
	{
		$result = new Product_Model($id);
		$result->delete();
		
		url::redirect('product');
	}
	
	public function search()
	{
		if(isset($_POST['keyword']))
		{
		    $block = new Block_Model();
		    $product = new Product_Model();
			
			$view = new View('product/lists');
		
			$view->caption = 'Product List --- 搜索关键词：'.$_POST['type'].' 中包含 "'.$_POST['keyword'].'"';
			
			switch ($_POST['type'])
			{
				case 'id':
					$view->datas = $product->where('id', intval($_POST['keyword']))->find_all();
					break;
				case 'title':
					$view->datas = $product->where("title_cn LIKE '%".$_POST['keyword']."%'")
										   ->orwhere("title_en LIKE '%".$_POST['keyword']."%'")
										   ->orderby('updated_at', 'DESC')
										   ->find_all();
					break;
			}
		
			$view->id = '';
			$view->type = '';
			$view->blocks = $block->where('source_name', 'products')->find_all();
			$view->categories = self::getProductCategory();
			$view->series = self::getProductSeries();
			$view->blocks = self::getBlocksBySourceName('products');
			
			$this->template->content = $view->render();
		}
		else
		{
			url::redirect('product');
			exit;
		}
	}
	
	public function filter($type, $id, $page_no)
	{
		if($id==0)
		{
			url::redirect('product');
			exit;
		}
		
	    $block = new Block_Model();
	    $product = new Product_Model();
	 
		$view = new View('product/lists');
		
		switch ($type) 
		{
			case 'category':
				$category = new Product_Category_Model($id);
				$view->caption = 'Product List --- 分类名称：'.$category->title_cn;
				$this->pagination = new Pagination(array(
			        'base_url'    => 'product/filter/'.$type.'/'.$id, 
			        'uri_segment' => 5, 
					'items_per_page' => 10, 
			        'total_items' => $product->select('COUNT(*) AS records_found')
											 ->where('category_id', $id)
											 ->find()->records_found
			    ));
				$view->datas = $product->where('category_id', $id)
									   ->orderby('updated_at', 'DESC')
									   ->limit(10, (($page_no - 1) * 10))
									   ->find_all();
				break;
			case 'series':
				$series = new Product_Model($id);
				$view->caption = 'Product List --- 系列名称：'.$series->series;
				$this->pagination = new Pagination(array(
			        'base_url'    => 'product/filter/'.$type.'/'.$id, 
			        'uri_segment' => 5, 
					'items_per_page' => 10, 
			        'total_items' => $product->select('COUNT(*) AS records_found')
											 ->where('series', $series->series)
											 ->find()->records_found
			    ));
				$view->datas = $product->where('series', $series->series)
									   ->orderby('updated_at', 'DESC')
									   ->limit(10, (($page_no - 1) * 10))
									   ->find_all();
				break;
			case 'block':
				$b = new Block_Model($id);
				$view->caption = 'Product List --- 版块名称：'.$b->title;
				$this->pagination = new Pagination(array(
			        'base_url'    => 'product/filter/'.$type.'/'.$id, 
			        'uri_segment' => 5, 
					'items_per_page' => 10, 
			        'total_items' => $product->select('COUNT(*) AS records_found')
											 ->join('block_elements AS be', 'be.source_pk_id=products.id')
									   		 ->where('be.block_id', $id)
											 ->find()->records_found
			    ));
				$view->datas = $product->join('block_elements AS be', 'be.source_pk_id=products.id')
									   ->where('be.block_id', $id)
									   ->orderby('updated_at', 'DESC')
									   ->limit(10, (($page_no - 1) * 10))
									   ->find_all();
				break;
				
		}
		
		$view->id = $id;
		$view->type = $type;
		$view->categories = self::getProductCategory();
		$view->series = self::getProductSeries();
		$view->blocks = self::getBlocksBySourceName('products');
		
		$this->template->content = $view->render();
	}
	
	public function type()
	{
		$form = new Forge(NULL, 'Select Product Type');
		$form->dropdown('product_type_id')->label('Product Type')->options(self::getProductType())->rules('required');
		$form->submit('Save');
 
		if($form->validate())
		{
			url::redirect('product/create/'.$form->product_type_id->value, 301);
		}
		else
		{
			$this->template->content = $form->html();
		}	
	}
	
	protected function getProductSeries()
	{
		$model = new Product_Model();
		$result = $model->select('id, series, title_cn')
						->where('series is not null')
						->groupby('series')
						->find_all();
		
		$arr['0'] = '';
		
		foreach($result as $record)
		{
			$arr[$record->id] = $record->series;
		}

		return $arr;
	}
	
	protected function getBlocksBySourceName($source_name)
	{
		$block = new Block_Model();
		$result = $block->where('source_name', $source_name)
						->find_all();
		
		$arr['0'] = '';
		
		foreach($result as $record)
		{
			$arr[$record->id] = $record->title;
		}

		return $arr;
	}
	
	protected function getProductCategory()
	{
		//SELECT * FROM product_categories WHERE left_id>1 
		//AND right_id <(SELECT right_id FROM product_categories WHERE id=1) 
		//AND layer_id<=2 ORDER BY left_id
		
		$model = new Product_Category_Model();
		$result = $model->where('left_id>1')
						->where('right_id < (SELECT right_id FROM product_categories WHERE id=1)')
						->where('layer_id<=2')
						->orderby('left_id')
						->find_all();
		
		$arr['cn']['0'] = '';
		$arr['en']['0'] = '';
		
		foreach($result as $record)
		{
			if($record->layer_id == 1)
			{
				if(($record->right_id-$record->left_id) == 1)
				{
					$arr['cn'][$record->id] = $record->title_cn;
					$arr['en'][$record->id] = $record->title_en;
				}
				else
				{
					$arr['cn'][$record->title_cn] = array();
					$arr['en'][$record->title_en] = array();
					$parent_cn = $record->title_cn;
					$parent_en = $record->title_en;
				}
			}
			elseif ($record->layer_id == 2)
			{
				$arr['cn'][$parent_cn][$record->id] = $record->title_cn;
				$arr['en'][$parent_en][$record->id] = $record->title_en;
			}
		}

		return $arr['cn'];
	}
		
	protected function getProductType($array = TRUE)
	{
		$model = new Product_type_Model();
		$result = $model->find_all();
		
		if(!$array) return $result;
		
		$arr['cn'][''] = '';
		$arr['en'][''] = '';
		
		foreach($result as $record)
		{
			$arr['cn'][$record->id] = $record->title_cn;
			$arr['en'][$record->id] = $record->title_en;
		}

		return $arr[cookie::get('lang')];
	}
}